package com.laomuji.android.mvvm.utils

import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup


/**
 * 让View支持拖动
 * 会覆盖View的OnTouchListener
 * @author laomuji666
 * @since 2024/2/21
 */
class DragUtil {
    class OnTouchDrag(private val marginLayoutParams: ViewGroup.MarginLayoutParams) : View.OnTouchListener {
        private var pressedX = 0
        private var pressedY = 0
        override fun onTouch(v: View?, event: MotionEvent?): Boolean {
            if(v==null || event==null){
                return true
            }
            when (event.actionMasked) {
                MotionEvent.ACTION_DOWN -> {
                    pressedX = event.rawX.toInt()
                    pressedY = event.rawY.toInt()
                }
                MotionEvent.ACTION_MOVE -> {
                    val x = event.rawX.toInt()
                    val y = event.rawY.toInt()
                    val dx: Int = x - pressedX
                    val dy: Int = y - pressedY

                    marginLayoutParams.leftMargin += dx
                    marginLayoutParams.topMargin += dy
                    v.layoutParams = marginLayoutParams
                    pressedX = x
                    pressedY = y
                }
                MotionEvent.ACTION_UP -> {}
            }
            return true
        }
    }

    fun setOnTouchDrag(view: View, marginLayoutParams: ViewGroup.MarginLayoutParams) {
        view.setOnTouchListener(OnTouchDrag(marginLayoutParams))
    }
}